package com.gson;

import java.lang.reflect.Field;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class TestGson {

	public static void main(String[] args) {
		
		ServiceResponse sr = ServiceResponse.newInstance() ;
		
		sr.setRespCode(ResponseCode.SUCCESS);
		
		
		ResponseResult rr = newInstanceResponseResult(sr,null);
		
		String json = "" ;
		Gson gson1 = new Gson();
		gson1.fromJson(json,ResponseResult.class);
		System.out.println();
		
		
		Gson gson = new GsonBuilder()
				//.addDeserializationExclusionStrategy(strategy)
		        .setFieldNamingStrategy(new FieldNamingStrategy() {
		        	
		            public String translateName(Field arg0) {
		                if (arg0.getName().equals("data")) {
		                    return "custom-name";
		                } else if (arg0.getName().equals("message")) {
		                    return "custom-phone";
		                }
		                return null;
		            }

		        })
		        .create();

		    System.out.println(gson.toJson(rr));
		    
		   /* String userStr = "{\"custom-name\":\"userN\",\"custom-phone\":\"168\"}";
		    System.out.println(gson.fromJson(userStr, ResponseResult.class));*/
	}
	
	 /**
     * 跟据条件，返回相应的结果。
     *
     * @param response
     * @param dataKey
     * @return
     */
    public static ResponseResult newInstanceResponseResult(ServiceResponse response, String dataKey) {
        ResponseResult result = ResponseResult.newInstance();
        if (response.getRespCode().equals(ResponseCode.SUCCESS)) {
            result.setCode("1");
            result.setMessage("Success");
        } else if (response.getRespCode().equals(ResponseCode.SYS_ERROR)) {
            result.setCode("-1");
            result.setMessage("System abnormal");
        } else if (response.getRespCode().equals(ResponseCode.IllEGAL_PARAM)) {
            result.setCode("1002");
            result.setMessage("Parameter illegal");
        } else {    //其他自定义错误码不做转换
            result.setCode(response.getRespCode());
            result.setMessage(response.getRespMsg());
        }
        //初始化参数
        if (dataKey != null) {
        	Object resultValue = response.getResultValue(dataKey);
        	if(resultValue != null){
        		result.setData(response.getResultValue(dataKey));
        	}else{
        		// for anroid
            	//result.setData(new HashMap<>());
        		result.setData("");
        	}
        }else{
        	// for anroid
        	//result.setData(new HashMap<>());
        	result.setData("");
        }
        return result;
    }
}
